package com.mto.module.karaoke.portlet.util.comparator;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;

import com.liferay.portal.kernel.util.OrderByComparator;

public class KaraokeComparator extends OrderByComparator {

	private static final long serialVersionUID = -3000177972319808673L;
	private String orderByCol;
	private boolean ascending = false;
	
	public static final String ASC = " ASC";
	public static final String DESC = " DESC";

	public KaraokeComparator(String orderByCol, String orderByType) {
		this(orderByCol, "asc".equalsIgnoreCase(orderByType));
	}
	
	public KaraokeComparator(String orderByCol, boolean ascending) {
		this.ascending = ascending;
		this.orderByCol = orderByCol;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public int compare(Object obj1, Object obj2) {
		if(obj1 == null || obj2 == null) return 0;
		if(!obj1.getClass().equals(obj2.getClass())) return 0;
		try {
			Object v1 = PropertyUtils.getProperty(obj1, orderByCol);
			Object v2 = PropertyUtils.getProperty(obj2, orderByCol);
			if(v1 == null || v2 == null) return 0;
			if(v1 instanceof Comparable) {
				return ((Comparable) v1).compareTo((Comparable) v2);
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public String getOrderBy() {
		if (ascending) {
			return orderByCol + ASC;
		} else {
			return orderByCol + DESC;
		}
	}

	@Override
	public String[] getOrderByFields() {
		return new String[]{ orderByCol };
	}

	@Override
	public boolean isAscending() {
		return ascending;
	}

}
